'use strict';
const db = uniCloud.database();
const uniID = require('uni-id-common');
const SECRET_KEY = "mindSora@#";
const EXPIRES_IN = "2h";  // 令牌有效期

exports.main = async (event, context) => {
  const uniIDIns = uniID.createInstance({ context });

  let body = event;
  if (typeof event.body === 'string') {
    try {
      body = JSON.parse(event.body);
    } catch (err) {
      return { code: -1, message: "JSON解析失败", error: err.message };
    }
  }

  // 校验 Token
  const { uid } = await uniIDIns.checkToken(body.uniIdToken);
  if (!uid) {
    return { code: 403, message: "身份验证失败" };
  }

  try {
    // 查找当前咨询师的所有被预约记录
    const res = await db.collection("appoint_schedule")
      .where({ consultant: uid })
      .get();

    const appoint = await Promise.all(res.data.map(async item => {
      let token = "";
      if (item.uid) {
        const tokenRes = await uniIDIns.createToken({ uid: item.uid });
        token = tokenRes.token;
      }

      return {
		appointId:item._id,
        day: item.day,
        appointedSlot: item.appointedSlot,
        uniIdToken: token
      };
    }));

    return {
      success:true,
      message: `查询成功，共 ${appoint.length} 条记录`,
      appoint
    };

  } catch (error) {
    console.error("数据库查询失败:", error);
    return {
      success: false,
      message: "数据库查询失败",
      error: error.message
    };
  }
};
